using UnityEngine;
using Spine;
using Spine.Unity;
using UnityEngine.UI;
using System;
using QFramework;
using static GiftManager;
[System.Serializable]
public class Student : MonoBehaviour
{
    private string studentId; // 学生 ID
    private string avatar; // 学生头像的路径或 URL
    private string nickname; // 学生昵称
    public StudentLevel level; // 学生级别


    private string[] talkOptions;
    public Image studentImageTalk;
    public Image studentImageAvatar;
    public Text studentTextNickname;

    public GameObject studentAnswerObject;

    public SkeletonGraphic studentLevelAnima;


    //todo 客户端维护没什么意义的字段 可以删除
    private int totalQuestions = 0; // 答题次数
    //todo 客户端维护没什么意义的字段 可以删除
    private int correctAnswers = 0; // 答对次数
    private int beishu = 1; // 倍数

    private Boolean ChiTiZhengQue = false; // 记录是不是送了此题正确

    //todo 从后台更新获取
    private int jifen = 0; // 总积分数

    private Boolean TiaoZhanNo1 = false;

    private int liansheng = 0;

    private int SingleTiJifen = 0;//单题获得的积分

    public int answer = 0; // 学生的答案，0代表未答题，1代表A，2代表B，3代表C，4代表D;

    private int classType = 0; // 0代表个人赛，1代表左边，2代表右边

    // 在Student类中增加变量

    // 构造函数
    public Student(string studentId, string avatar, string nickname, StudentLevel level = StudentLevel.YouErYuan, int classType = 0)
    {
        this.studentId = studentId;
        this.avatar = avatar;
        this.nickname = nickname;
        this.level = level; // 默认等级
        this.totalQuestions = 0;
        this.correctAnswers = 0;
        this.beishu = 1;
        this.jifen = 0;
        this.classType = classType;
        this.answer = 0;
        this.TiaoZhanNo1 = false;
        this.SingleTiJifen = 0;
        this.ChiTiZhengQue = false;
        this.liansheng = 0;
    }

    public void InitStudentInfo(
        string studentId,
        string avatar,
        string nickname,
        StudentLevel level = StudentLevel.YouErYuan,
        int classType = 0,
        int jifen = 0,
        int totalQuestions = 0,
        int correctAnswers = 0,
        int beishu = 1,
        int answer = 0,
        int liansheng = 0
    )
    {
        this.studentId = studentId;
        this.avatar = avatar;
        this.nickname = nickname;
        this.level = level; // 默认等级
        this.totalQuestions = totalQuestions;
        this.correctAnswers = correctAnswers;
        this.beishu = beishu;
        this.jifen = jifen;
        this.classType = classType;
        this.answer = answer;
        TiaoZhanNo1 = false;
        SingleTiJifen = 0;
        ChiTiZhengQue = false;
        this.liansheng = liansheng;
    }

    // 增加答题次数
    public void incrementTotalQuestions()
    {
        totalQuestions++;
    }

    // 增加答对次数
    public void incrementCorrectAnswers()
    {
        correctAnswers++;
    }

    //获得答对次数
    public int getCorrectAnswers()
    {
        return correctAnswers;
    }

    // 获取正确率
    public string getAccuracy()
    {
        //转为百分数
        float accuracy = totalQuestions > 0 ? ((float)correctAnswers / totalQuestions) * 100 : 0;
        return accuracy.ToString("F1") + "%";
    }

    public void setLiansheng(int liansheng)
    {
        this.liansheng = liansheng;
    }
    public int getLiansheng()
    {
        return liansheng;
    }

    public string getStudentID() { return studentId; }

    public int getAnswer() { return answer; }

    public void setAnswer(int answer) { this.answer = answer; }

    public int getBeishu() { return beishu; }
    public void setBeishu()
    {
        if (this.beishu < 16) {
            this.beishu = this.beishu * 2;
        }
    }
            

    public void setChiTiZhengQue(Boolean ChiTiZhengQue)
    {
        this.ChiTiZhengQue = ChiTiZhengQue;
    }
    public Boolean getChiTiZhengQue()
    {
        return ChiTiZhengQue;
    }
    public void setTiaoZhanNo1(Boolean tiaoZhanNo1)
    {
        this.TiaoZhanNo1 = tiaoZhanNo1;
    }
    public Boolean getTiaoZhanNo1()
    {
        return TiaoZhanNo1;
    }
    //单题结算后需要重置的内容
    public void ResetAfterSingleTiSeletment()
    {
        this.beishu = 1;
        this.answer = 0;
        this.SingleTiJifen = 0;
        this.ChiTiZhengQue = false;
        this.TiaoZhanNo1 = false;
    }

    public int getJifen() { return jifen; }

    public void addJifen(int jifen)
    {
        this.jifen += jifen;
    }
    public void setClassType(int classType) { this.classType = classType; }
    public int getClassType() { return classType; }

    public string getAvatarUrl() { return avatar; }
    public string getNickname() { return nickname; }

    public int getTotalQuestions() { return totalQuestions; }

    public void SetSingleTiJifen(int jifen) { this.SingleTiJifen = jifen; }

    public int GetSingleTiJifen() { return this.SingleTiJifen; }

    void Awake()
    {
        // 确保数组在Awake中被初始化
        if (talkOptions == null || talkOptions.Length == 0)
        {
            talkOptions = new string[] {
                "老师来了！！",
                "班主任在后门！",
                "下节什么课？",
                "作业是啥？",
                "借我支笔！",
                "橡皮给我！",
                "你做到第几题了？",
                "帮我传给李斌！",
                "王伟，他打我。",
                "王芳，我爱你。",
                "哈哈哈，他放屁了。",
                "嘤嘤嘤，他不让我抄作业。",
                "他不跟我玩了。",
                "我饿了。",
                "这道题我不会。",
                "好简单，so easy。",
                "我同桌上课吃东西。"
            };
            Debug.Log($"Student {gameObject.name}: talkOptions initialized with {talkOptions.Length} items");
        }
    }

    void Start()
    {
        StringEventSystem.Global.Register(EventID.PlayGiftAnimation, (object[] _params) =>
            {
                if ((AnimaName)_params[0] == AnimaName.StudentSpeak)
                {
                    //进一步判断id是否一样
                    GameObject paramGo = _params[1] as GameObject;
                    Student paramStudent = paramGo ? paramGo.GetComponentInChildren<Student>() : null;
                    if (studentId == paramStudent.getStudentID())
                    {
                        SetStudentImageTalk();
                    }

                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

        StringEventSystem.Global.Register(EventID.ShowAnswer, (string[] _params) =>
            {
                if (_params == null)
                {
                    Debug.Log("ShowAnswer事件参数为空");
                    return;
                }
                if (_params.Length != 2)
                {
                    Debug.Log("ShowAnswer事件参数长度不为2");
                    return;
                }
                if (_params[1] != studentId)
                {
                    Debug.Log("ShowAnswer事件参数id不匹配");
                    return;
                }

                if (_params != null && _params.Length == 2 && _params[1] == studentId)
                {
                    Debug.Log($"学生{studentId}选择了选项{_params[0]}");
                    showStudentAnswer(_params[0]);
                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        StringEventSystem.Global.Register(EventID.HideAnswer, () =>
            {
                HideStudentAnswer();
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

        //test间隔3秒播放学生说话内容
        // InvokeRepeating("SetStudentImageTalk", 3f, 3f);
        //test 学生升级动画
        // InvokeRepeating("PlayStudentLevelAnima", 5f, 5f);


        //接收学生升级事件
        StringEventSystem.Global.Register(EventID.StudentUpLevel, (string _params) =>
            {
                if (_params == null)
                {
                    Debug.Log("StudentUpLevel事件参数为空");
                    return;
                }
                if (_params != studentId)
                {
                    Debug.Log("StudentUpLevel事件参数id不匹配");
                    return;
                }

                if (_params != null && _params == studentId)
                {
                    Debug.Log($"学生{studentId}升级了");
                    PlayStudentLevelAnima();
                }
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
    }
    //播放行走动画
    public void PlayWalkAnimation(float timeScale = 1.0f)
    {
        // 获取学生节点
        Transform studentTransform = transform.Find("StudentAnim");
        if (studentTransform == null)
        {
            Debug.LogError("Child object 'StudentAnim' not found on " + gameObject.name, gameObject);
            return;
        }
        SkeletonGraphic student_skeletonGraphic = studentTransform.GetComponent<SkeletonGraphic>();
        if (student_skeletonGraphic == null)
        {
            Debug.LogError("SkeletonGraphic component not found on 'StudentAnim' child of " + gameObject.name, gameObject);
            return;
        }

        if (student_skeletonGraphic.AnimationState != null)
        {
            // 播放行走动画
            TrackEntry entry = student_skeletonGraphic.AnimationState.SetAnimation(0, "zoulu", true);
            entry.TimeScale = timeScale;
        }
        else
        {
            Debug.LogError("AnimationState is null for SkeletonGraphic on " + gameObject.name, gameObject);
        }
    }

    //播放站立动画
    public void PlayStandAnimation()
    {
        // 获取学生节点
        Transform studentTransform = transform.Find("StudentAnim");
        if (studentTransform == null)
        {
            Debug.LogError("Child object 'StudentAnim' not found on " + gameObject.name, gameObject);
            return;
        }
        SkeletonGraphic student_skeletonGraphic = studentTransform.GetComponent<SkeletonGraphic>();
        if (student_skeletonGraphic == null)
        {
            Debug.LogError("SkeletonGraphic component not found on 'StudentAnim' child of " + gameObject.name, gameObject);
            return;
        }

        if (student_skeletonGraphic.AnimationState != null)
        {
            // 播放站立动画
            TrackEntry entry = student_skeletonGraphic.AnimationState.SetAnimation(0, "changtai", true);
            entry.TimeScale = 1.0f; // 确保站立动画以正常速度播放
        }
        else
        {
            Debug.LogError("AnimationState is null for SkeletonGraphic on " + gameObject.name, gameObject);
        }
    }
    //更新信息
    public void UpdateInfo(string avatar, string nickname, Action callback)
    {
        Debug.Log("更新头像信息：" + avatar);
        SetStudentImageAvatar(avatar, callback);
        studentTextNickname.text = nickname;
    }
    //设置学生头像
    public void SetStudentImageAvatar(string avatar, Action callback)
    {
        ImageLoader.Instance.LoadImageFromUrl(studentImageAvatar, avatar, callback); // 设置头像
    }

    //设置说话动画
    public void SetStudentImageTalk(string p_talk = null)
    {
        if (studentImageTalk == null)
        {
            Debug.LogError($"studentImageTalk is null on GameObject {gameObject.name}. Please assign the Image component in the Unity Inspector.");
            return;
        }

        if (p_talk == null)
        {
            if (talkOptions == null || talkOptions.Length == 0)
            {
                Debug.LogError($"talkOptions is null or empty on GameObject {gameObject.name}. Attempting to reinitialize...");
                // 尝试重新初始化
                talkOptions = new string[] {
                "老师来了！！",
                "班主任在后门！",
                "下节什么课？",
                "作业是啥？",
                "借我支笔！",
                "橡皮给我！",
                "你做到第几题了？",
                "帮我传给李斌！",
                "王伟，他打我。",
                "王芳，我爱你。",
                "哈哈哈，他放屁了。",
                "嘤嘤嘤，他不让我抄作业。",
                "他不跟我玩了。",
                "我饿了。",
                "这道题我不会。",
                "好简单，so easy。",
                "我同桌上课吃东西。"
            };
                if (talkOptions == null || talkOptions.Length == 0)
                {
                    Debug.LogError($"Failed to reinitialize talkOptions on GameObject {gameObject.name}");
                    return;
                }
            }

            int randomIndex = UnityEngine.Random.Range(0, talkOptions.Length);
            string talk = talkOptions[randomIndex];
            Debug.Log($"Selected talk option: {talk} (index: {randomIndex})");

            studentImageTalk.gameObject.SetActive(true);
            Text talkText = studentImageTalk.transform.Find("Text")?.GetComponent<Text>();
            if (talkText == null)
            {
                Debug.LogError($"Text component not found in studentImageTalk on GameObject {gameObject.name}");
                return;
            }
            talkText.text = talk;
            Invoke("HideStudentImageTalk", 3f);//3秒后隐藏说话动画
        }
        else
        {
            studentImageTalk.gameObject.SetActive(true);
            Text talkText = studentImageTalk.transform.Find("Text")?.GetComponent<Text>();
            if (talkText == null)
            {
                Debug.LogError($"Text component not found in studentImageTalk on GameObject {gameObject.name}");
                return;
            }
            talkText.text = p_talk;
        }
    }
    //隐藏说话动画
    private void HideStudentAnswer()
    {
        studentAnswerObject.gameObject.SetActive(false);
    }

    private void HideStudentImageTalk()
    {
        studentImageTalk.gameObject.SetActive(false);
    }

    private void showStudentAnswer(string p_answer)
    {
        studentAnswerObject.gameObject.SetActive(true);
        studentAnswerObject.GetComponentInChildren<Text>().text = p_answer;
    }
    //学生升级动画
    public void PlayStudentLevelAnima()
    {
        if  (studentLevelAnima == null){
            //从父节点找
            GameObject parent = transform.parent.gameObject;
            studentLevelAnima = parent.transform.Find("upLevelAnim").GetComponent<SkeletonGraphic>();
        } 
        studentLevelAnima.gameObject.SetActive(true);
        studentLevelAnima.AnimationState.SetAnimation(0, "animation", false);
        //动画完成隐藏
        studentLevelAnima.AnimationState.Complete += (TrackEntry trackEntry) =>
        {
            studentLevelAnima.gameObject.SetActive(false);
        };
    }
}


// 定义学生等级的枚举
public enum StudentLevel
{
    YouErYuan, // 默认等级
    XiaoXueSheng,
    ChuZhongSheng,
    GaoZhongSheng,
    DaXueSheng,
    BoShiSheng
}

//仅用于 获取学生信息json使用
[System.Serializable]
public class StudentData
{
    public int id; // 学生 ID
    public string nick; // 学生昵称
    public string avata; // 学生头像的路径或 URL

    // 转换为 Student 对象
    public Student ToStudent()
    {
        return new Student(id.ToString(), avata, nick);
    }
}
